package com.reworkssm.mybatisdemo.service;

import com.reworkssm.mybatisdemo.config.security.TokenService;
import com.reworkssm.mybatisdemo.domain.Account;
import com.reworkssm.mybatisdemo.domain.Login;
import com.reworkssm.mybatisdemo.persistence.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import static org.apache.commons.codec.digest.DigestUtils.md5Hex;
import java.math.BigInteger;
import java.security.MessageDigest;

@Service
public class AccountService{
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private TokenService tokenService;

    public AccountService() {
    }

    public Account login(Login account) {
        return accountMapper.getAccountByUsernameAndPassword(account);
    }

    public Account getAccount(String username) {
        return accountMapper.getAccountByUsername(username);
    }

    // ideally this shall be handled by DTO
    public String getLoginToken(Login loginaccount) {
        loginaccount.setPassword(getMD5(loginaccount.getPassword()));
        Account account = accountMapper.getAccountByUsernameAndPassword(loginaccount);
        String token = tokenService.createToken(account);
        if (token != null) return token;
        return "";
    }

    public Account getAccount(String username, String password) {
        Login account = new Login();
        account.setUsername(username);
        account.setPassword(getMD5(password));
        return accountMapper.getAccountByUsernameAndPassword(account);
    }


    @Transactional
    public void insertAccount(Account account) {
        account.setPassword(getMD5(account.getPassword()));
        accountMapper.insertAccount(account);
        accountMapper.insertProfile(account);
        accountMapper.insertSignon(account);
    }

    @Transactional
    public void updateAccount(Account account) {
        account.setPassword(getMD5(account.getPassword()));
        accountMapper.updateAccount(account);
        accountMapper.updateProfile(account);
        if (account.getPassword() != null && account.getPassword().length() > 0) {
            accountMapper.updateSignon(account);
        }
    }

    public String getMD5(String str) {
/*        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }*/
        return md5Hex(str).toUpperCase();
    }
}
